#include "lettershell/shell.h"
#include "bsp.h"
#include "bsp_gnss.h"
#include "bsp_modem.h"

#include "hal_adapter.h"
#include "lowpower/include/low_power.h"
#include "misc/misc_system.h"
#include "comm/co_heartbeat.h"

extern sleep_item_t *sleep_item[];
extern uint32_t sleep_item_count;

int32_t iot_enter_lowpower(void)
{
    // icm42670_sensor_lowpower_initialize();

    bsp_gnss_power_off(); // 20ma
    // bsp_modem_powerctrl_off();  //13ma

    __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, 0);

    /*RTCCLK = 32kHZ, WakeUpTimer = 32/16 = 2KHZ */
    HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 3 * 2000, RTC_WAKEUPCLOCK_RTCCLK_DIV16, 0);

    // drv_stop();
    bsp_enter_lowpower(); // 8-10ma

    // icm42670_sensor_initialize();
    bsp_gnss_power_on();

    return 0;
}

SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 iot_lowpower, iot_enter_lowpower, function test set iot into lowpower);

/**
 * @brief 打印休眠条件的状态
 * @return int32_t
 */
int32_t iot_lowpower_print(void)
{

    // @TODO:增加打印所有限制休眠的条件

    return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 lowpower_status, iot_lowpower_print, function test set iot into lowpower);


/***
**  列出当前的设备信息
*******************************************************************************/
static int do_cmd_power(void)
{
    sleep_item_t    *item = NULL;
    uint32_t        sleep = 0;
    const char      *line = "+------------------------------------------------+\r\n";

    printf(line);
    printf(" work mode           : %s\r\n", (WORK_MODE_NORMAL == misc_get_work_mode()) ? "normal" : "sleep");
    printf(" active status       : %s\r\n", (ACTIVE == misc_get_active_state()) ? "active" : "unactive");
    printf(" co mcu sleep counter: %d/%d\r\n", co_mcu_timeout(), CO_MCU_HB_POWEROFF_INTERVAL);
    // @todo: 增加打印低功耗时间和正常工作时长，以及低功耗时长百分比
    printf(line);
    printf("|      name        canstop        stoptime      |\r\n");
    for (int i = 0; i < sleep_item_count; i++) {
        item = sleep_item[i];
        if (item->canstop)
            sleep = item->canstop();

        printf("|      %-15s%-12s%-14u|\r\n", item->name, sleep ? "yes" : "no", sleep);
    }
    printf(line);
    return 0;
}

SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC) | SHELL_CMD_DISABLE_RETURN,
                 lowpower, do_cmd_power, show iot lowpower vote);
